package gui;

import gui.admin.ManageAdmin;
import gui.user.PassengerManageForm;
import gui.user.RegisterForm;
import info.Admin;
import info.Passenger;
import messages.AdminLoginRequestMessage;
import messages.AdminLoginResponseMessage;
import messages.user.LoginQueryStatus;
import messages.user.LoginRequestMessage;
import messages.user.LoginResponseMessage;
import server.MessageServer;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;

public class LoginForm extends JFrame{
    private JTextField accountField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;

    private String[] identityTypes = {"user","admin"};
    private JComboBox<String> identityComboBox;
    private Passenger passenger = new Passenger();
    private boolean isConnected = false;
    private String serverIP = "localhost";

    private Admin admin = new Admin();

    public LoginForm(){
        super("登录");
        setSize(450, 250);

        // 创建登录面板
        JPanel loginPanel = new JPanel(new GridLayout(4, 2));

        // 添加账户输入框
        loginPanel.add(new JLabel("账户:", JLabel.CENTER));
        accountField = new JTextField(20);
        loginPanel.add(accountField);

        // 添加密码输入框
        loginPanel.add(new JLabel("密码:", JLabel.CENTER));
        passwordField = new JPasswordField(20);
        loginPanel.add(passwordField);

        loginPanel.add(new JLabel("身份：",JLabel.CENTER));
        identityComboBox = new JComboBox<>(identityTypes);
        identityComboBox.setSelectedIndex(0);
        loginPanel.add(identityComboBox);

        // 添加登录按钮并添加事件监听器
        registerButton = new JButton("注册");
        registerButton.addActionListener(e -> {
            SwingUtilities.invokeLater(RegisterForm::new);
        });
        loginButton = new JButton("登录");
        loginButton.addActionListener(e -> {
            if(identityComboBox.getSelectedIndex() == 0){
                SwingUtilities.invokeLater(()->{
                    LoginQueryStatus lqs = verifyAccount(accountField.getText(),
                            String.valueOf(passwordField.getPassword()));
                    if(lqs == LoginQueryStatus.SUCCESS){
                        new PassengerManageForm(passenger);
                        dispose();
                    }else if(lqs == LoginQueryStatus.PWD_ERROR){
                        JOptionPane.showMessageDialog(this, "密码错误，请重新输入");
                        passwordField.setText(null);
                    }else{
                        JOptionPane.showMessageDialog(this, "用户不存在！");
                        accountField.setText(null);
                        passwordField.setText(null);
                    }
                });
            }else if(identityComboBox.getSelectedIndex() == 1){
                LoginQueryStatus lqs = verifyAdminAccount(accountField.getText(),
                        String.valueOf(passwordField.getPassword()));
                if (lqs == LoginQueryStatus.SUCCESS) {
                    new ManageAdmin(admin);
                    dispose();
                } else if (lqs == LoginQueryStatus.PWD_ERROR) {
                    JOptionPane.showMessageDialog(this, "密码错误，请重新输入");
                    passwordField.setText(null);
                } else {
                    JOptionPane.showMessageDialog(this, "管理员不存在！");
                    accountField.setText(null);
                    passwordField.setText(null);
                }
            }
        });
        loginPanel.add(registerButton);
        loginPanel.add(loginButton);

        add(loginPanel);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        setVisible(true);
        isConnected = MessageServer.getInstance().connectToServer();
    }


    private LoginQueryStatus verifyAccount(String account,String pwd){
        if (!isConnected) {
            int maxRetry = 10, j = 0;
            while (j++ < maxRetry) {
                if(MessageServer.getInstance().connectToServer())
                    break; // 连接成功
            }
        }

        if (!isConnected){
            JOptionPane.showMessageDialog(this, "Failed to connect to server: " + serverIP);
            return null;
        }

        LoginRequestMessage login_req_msg = new LoginRequestMessage(account,pwd);
        LoginResponseMessage login_ack_msg;

        try {
            MessageServer.getInstance().getOos().writeObject(login_req_msg);
            System.out.println("客户端发送请求成功！"+login_req_msg);
            login_ack_msg = (LoginResponseMessage) MessageServer.getInstance().
                    getOis().readObject();
            System.out.println("客户端收到服务端的响应成功！"+login_ack_msg);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        if(login_ack_msg.getPassenger() != null && login_ack_msg.getQueryStatus() == LoginQueryStatus.SUCCESS){
            passenger.setIdno(login_ack_msg.getPassenger().getIdno());
            passenger.setPwd(login_ack_msg.getPassenger().getPwd());
            passenger.setpName(login_ack_msg.getPassenger().getpName());
            passenger.setTelephone(login_ack_msg.getPassenger().getTelephone());
            return login_ack_msg.getQueryStatus();
        }else{
            return login_ack_msg.getQueryStatus();
        }

    }
    private LoginQueryStatus verifyAdminAccount(String account, String pwd) {
        if (!isConnected) {
            int maxRetry = 10, j = 0;
            while (j++ < maxRetry) {
                if (MessageServer.getInstance().connectToServer())
                    break; // 连接成功
            }
        }

        if (!isConnected) {
            JOptionPane.showMessageDialog(this, "Failed to connect to server: " + serverIP);
            return null;
        }

        AdminLoginRequestMessage adminLoginReqMsg = new AdminLoginRequestMessage(account, pwd);
        AdminLoginResponseMessage adminLoginAckMsg;


        try {
            MessageServer.getInstance().getOos().writeObject(adminLoginReqMsg);
            System.out.println("客户端发送请求成功！" + adminLoginReqMsg);
            adminLoginAckMsg = (AdminLoginResponseMessage) MessageServer.getInstance().getOis().readObject();
            System.out.println("客户端收到服务端的响应成功！" + adminLoginAckMsg);
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        if (adminLoginAckMsg.getAdmin() != null && adminLoginAckMsg.getQueryStatus() == LoginQueryStatus.SUCCESS) {
            admin.setIdno(adminLoginAckMsg.getAdmin().getIdno());
            admin.setPwd(adminLoginAckMsg.getAdmin().getPwd());
            admin.setName(adminLoginAckMsg.getAdmin().getName());
            admin.setTelephone(adminLoginAckMsg.getAdmin().getTelephone());
            return adminLoginAckMsg.getQueryStatus();
        } else {
            return adminLoginAckMsg.getQueryStatus();
        }
    }

}
